import type { ProxyOptions } from 'vite'
import type { IncomingMessage, ServerResponse } from 'http'

/**
 * 动态生成 vite 代理
 * @param proxyList  代理列表
 * @param prefix 代理前缀
 * @returns 代理配置列表
 */
export const getDownloadProxies = (proxyList: string[], prefix: string): Record<string, string | ProxyOptions> => {

  const proxyOptionsList: Record<string, string | ProxyOptions> = {}

  proxyList.forEach((proxy) => {
    proxyOptionsList[`${prefix}/${proxy}`] = {
      target: proxy, // 占位值
      changeOrigin: true,
      rewrite: (path: string) => {
        console.log(path.replace(`${prefix}/${proxy}`, ''))
        return path.replace(`${prefix}/${proxy}`, '')
      },
      bypass(req: IncomingMessage, res: ServerResponse<IncomingMessage> | undefined, options: ProxyOptions) {
        console.log('[req]', req)
        const proxyUrl = new URL(options?.rewrite?.(req.url || '') || '', (options.target) as string)?.href || ''
        req.headers['x-req-proxyUrl'] = proxyUrl
        req.headers['Referer'] = req.url
        res?.setHeader('x-res-proxyUrl', proxyUrl)
      }
    }
  })

  return proxyOptionsList
}
